/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var todo = "";
var msgTimeOut = 3000;
var isShowingMsg = false;

var winMsgDlg;
function beginMessageDlg(userId,userName,setTitle)
{
    if(winMsgDlg==null)
    {
        winMsgDlg = new Ext.Window({
            el:'divMsgFrame',
            userId :1,
            title:'与 '+userName+' 对话',
            closable:true,
            width:356,
            closeAction:'hide',
            resizable:false,
            autoHeight:true,
            items:[divMsgDlg],
            buttons:[
                {text:'发送',handler:function(){sendMsg();}},
                {text:'关闭',handler:function(){winMsgDlg.hide();}}
            ]
        });
    }
    winMsgDlg.userId = userId ;
    winMsgDlg.setTitle('发消息给 '+userName);
    document.getElementById('divMsgDlg').getElementsByTagName('input')[0].value='';
    document.getElementById('divMsgDlg').getElementsByTagName('textarea')[0].value='';
    if(setTitle!=null)
    {
        document.getElementById('divMsgDlg').getElementsByTagName('input')[0].value='回复：'+setTitle;
    }
    winMsgDlg.show();
}

function sendMsg()
{
    var conn = new Ext.data.Connection();
      // 发送异步请求
    conn.request({
      // 请求地址
        url: '../UserController',
        method: 'POST',
        params:'action=postmsg&recvId='+winMsgDlg.userId+'&msgtitle='+document.getElementById('msgTitle').value+'&msgContent='+document.getElementById('textMsg').value,
        // 指定回调函数
        callback: callback
    });
    //回调函数
    function callback(options, success, response){
        if(success&&response.responseText=='消息已发送'){
          // 如果成功则使用Ext将JSON字符串转换为JavaScript对象
          //var jsonObj = Ext.util.JSON.decode(response.responseText);
          //　到这就可以取你想要的东东了
          //Ext.Msg.alert('消息提示',response.responseText);
          TipMessageShow('提示','消息已发送');
          winMsgDlg.hide();
          storeMsg.load({params:{start:0, limit:25}});
        }
        else if(success)
        {
            Ext.Msg.alert('错误提示',response.responseText);
        }
        else
        {
            Ext.Msg.alert('错误提示','连接服务器失败');
        }
    }
}

var checkMessageConn = new Ext.data.Connection();
function checkMessage()
{   //alert('failed');
      // 发送异步请求
    checkMessageConn.request({
      // 请求地址
        url: '../UserController',
        method: 'POST',
        params:'action=checkmsg',
        // 指定回调函数
        callback: CheckMsgCallback
    });
    
    setTimeout(checkMessage,msgTimeOut);
}
//回调函数
function CheckMsgCallback(options, success, response){
    if(success){
        if(response.responseText==0)
            ;
        else if(response.responseText==1)
            showMessageInfo();
        else
            showMessageList();
    }
    else
        alert('failed');
}

var tipMsg;
function showMessageInfo()
{
    if(isShowingMsg)
        return;
    var mgr = new Ext.Updater("divMsgTipDlg");
    mgr.update({
        url: "user/messages.jsp", 
            params: "type=new",
            text: "正在加载用户数据..."
        });
    mgr.on("update", function(){
            if(tipMsg ==null)
                tipMsg = new Ext.Window({
                title:'您有一条消息',
                closable:true,
                height :100,
                width:200,
                items:[divMsgTipDlg]
            });
            tipMsg.setPosition(document.body.clientWidth-200,document.body.clientHeight-100);
            tipMsg.show();
            isShowingMsg = true;
        });
}

function showMessageList()
{
    //alert('showMessageList');
}

var cmMsg;
var gridMsg;
var storeMsg;
function viewMessages(typeParam)
{
    todo = typeParam;
   // Ext.QuickTips.init();
    if(storeMsg == null)
    {
        storeMsg = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: 'user/messages.jsp'//+typeParam?type=unread
            }),

            // create reader that reads the Topic records
            reader: new Ext.data.JsonReader({
                root: 'root',
                totalProperty: 'totalCount',
                fields: [
                    {name: 'title'},
                    {name: 'cont'},
                    {name: 'time'},
                    {name: 'read'},
                    {name: 'recv'},
                    {name: 'send'},
                    {name: 'sname'},
                    {name: 'rname'},
                    {name: 'id'},
                    {name: 'img'}
                ]
            })
        });
    }
    function renderInfo(value, p, record)
    {
        if(todo == 'sent')
        {
            if(record.data.read=='true')
                return String.format('<table><tr><td align="left">接收者 <a href="#" onclick=showUserInfo({2},"{3}")  onmouseover="showSimpleViewOfUser({2})" onmouseout="hideSimpleViewOfUser()">{0}</a></td></tr><tr><td align="left">发送时间 {1}</td></tr><tr><td align="left">状态 <img id="img{2}" alt="信封已被打开" src="../images/messages/read.jpg"></td></tr></table>',record.data.rname,record.data.time,record.data.recv,record.data.rname);
            else
                return String.format('<table><tr><td align="left">接收者 <a href="#" onclick=showUserInfo({2},"{3}")  onmouseover="showSimpleViewOfUser({2})" onmouseout="hideSimpleViewOfUser()">{0}</a></td></tr><tr><td align="left">发送时间 {1}</td></tr><tr><td align="left">状态 <img id="img{2}" alt="信封未被打开" src="../images/messages/unread.jpg"></td></tr></table>',record.data.rname,record.data.time,record.data.recv,record.data.rname);
        }
        else
        {
            return String.format('<table><tr><td align="left">来自 <a href="#" onclick=showUserInfo({2},"{3}")  onmouseover="showSimpleViewOfUser({2})" onmouseout="hideSimpleViewOfUser()">{0}</a></td></tr><tr><td align="left">发出时间 {1}</td></tr></table>',record.data.sname,record.data.time,record.data.send,record.data.sname);
        }
    }
    function renderTitle(value, p, record)
    {
        if(todo == 'sent')
        {
            return String.format('<table><tr><td align="left"><a href="#" onclick=showMsgContent("{2}")>{0}</a></td></tr><tr><td align="left"><div style="display:none" id="divmsg{2}">{1}</div></td></tr></table>',value,record.data.cont,record.data.id);
        }
        else
        {
          if(record.data.read=='true')
              return String.format('<table><tr><td align="left"><img id="img{2}" alt="已读" src="../images/messages/read.jpg"><a href="#" onclick=showMsgContent("{2}")>{0}</a></td><td align="right"><a href="#" onclick=beginMessageDlg("{3}","{4}","{0}")>回复</a></td></tr><tr><td align="left"><div style="display:none" id="divmsg{2}">{1}</div></td></tr></table>',value,record.data.cont,record.data.id,record.data.send,record.data.sname);
          else
              return String.format('<table><tr><td align="left"><img id="img{2}" alt="未读" src="../images/messages/unread.jpg"><a href="#" onclick=showMsgContent("{2}")>{0}</a></td><td align="right"><a href="#" onclick=beginMessageDlg("{3}","{4}","{0}")>回复</a></td></tr><tr><td align="left"><div style="display:none" id="divmsg{2}">{1}</div></td></tr></table>',value,record.data.cont,record.data.id,record.data.send,record.data.sname);          
        }
    }
    
    var sm = new Ext.grid.CheckboxSelectionModel();

    if(cmMsg == null)
    {
        cmMsg = new Ext.grid.ColumnModel([
            new Ext.grid.RowNumberer(),
            sm,
            {
               id: 'topic',
               header: "消息",
               dataIndex: 'title',
               width: 500,
               renderer: renderTitle
            },{
               header: "",
               dataIndex: 'time',
               width: 200,
               sortable: false,
               align: 'center',
               renderer: renderInfo
            }]);
        cmMsg.defaultSortable = true;
    }

    if(gridMsg == null)
    {
        gridMsg = new Ext.grid.GridPanel({
            el:'divTabMessage',
            store: storeMsg,
            cm: cmMsg,
            trackMouseOver:true,
            sm: sm,//new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
            iconCls:'icon-grid',
            autoScroll: true,
            border: false,
            bbar: new Ext.PagingToolbar({
                pageSize: 25,
                store: storeMsg,
                displayInfo: true,
                displayMsg: '显示的消息 {0} - {1} of {2}',
                emptyMsg: "没有相关的消息",
                items:[
                    '-',{
                        text: '删除',
                        handler: function(btn, pressed){
                            if(sm.getCount()==0)
                            {
                                TipMessageShow('提示','请选择要删除的消息');
                                return;
                            }
                            Ext.MessageBox.show({
                                title: '提示',
                                msg: '您确定要删除所选消息吗？',
                                width:200,
                                icon: Ext.MessageBox.QUESTION,
                                buttons: Ext.MessageBox.OKCANCEL,
                                fn :function(btn, text){
                                    if (btn != 'ok'){
                                        return
                                    }
                                    else
                                    {
                                        var selectedArray = sm.getSelections();
                                        var conn = new Ext.data.Connection();
                                        for(i=0;i<sm.getCount();i++)
                                        {
                                            //alert(selectedArray[i].data.id);
                                            conn.request({
                                              // 请求地址
                                                url: '../UserController',
                                                method: 'POST',
                                                params:'action=delmsg&msgId='+selectedArray[i].data.id,
                                                // 指定回调函数
                                                callback: callback
                                            });
                                        }
                                        //回调函数
                                        function callback(options, success, response){
                                            if(success&&response.responseText=='ok'){
                                              //TipMessageShow('提示','');
                                              storeMsg.load({params:{start:0, limit:25}});
                                            }
                                            else if(success)
                                            {
                                                Ext.Msg.alert('错误提示',response.responseText);
                                            }
                                            else
                                            {
                                                Ext.Msg.alert('错误提示','连接服务器失败');
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    }
                ]
            })
        });
    }
    //document.getElementById("divData").style.display='';
    //gridSearch.setHeight(document.getElementById("divData").clientHeight);
    gridMsg.render();
    storeMsg.on('beforeload',function(){
        Ext.apply(
        this.baseParams,
        {
            type : typeParam
        });
    });
    storeMsg.load({params:{start:0, limit:25}});
    tabCount++;
    var panMsg = new Ext.Panel({
        id:'tabMessage',
        title:"消息管理",
        //closable:true,
        closeAction:'hide',
        autoScroll:true,
        //items:[divSearchResult]
        el : divTabMessage
    });
    panel.add(panMsg);
    if(typeParam=='unread')
      cmMsg.setColumnHeader(0,'未读消息');
    else if(typeParam=='read')
      cmMsg.setColumnHeader(0,'未读消息');
    else if(typeParam=='sent')
    {
      cmMsg.setColumnHeader(0,'已发送的消息');
    }
    else if(typeParam=='all')
      cmMsg.setColumnHeader(0,'查看所有消息');
    panel.activate('tabMessage');
    //panel.render();
}

function showMsgContent(msgId)
{
    if(document.getElementById('divmsg'+msgId).style.display=="")
        document.getElementById('divmsg'+msgId).style.display="none";
    else
    {
        document.getElementById('divmsg'+msgId).style.display="";
        if(todo=='sent')
            return;
        //更新已读状态
        var conn = new Ext.data.Connection();
          // 发送异步请求
        conn.request({
          // 请求地址
            url: '../UserController',
            method: 'POST',
            params:'action=readmsg&msgId='+msgId,
            // 指定回调函数
            callback: callback
        });
        //回调函数
        function callback(options, success, response){
            if(success&&response.responseText=='ok'){
                //更新信封图标
                document.getElementById('img'+msgId).src='../images/messages/read.jpg';
            }
            else if(success)
            {
                Ext.Msg.alert('错误提示',response.responseText);
            }
            else
            {
                Ext.Msg.alert('错误提示','连接服务器失败,请重新登录');
            }
        }
    }
}